package blue.http.internal.core.net.response;

import blue.http.core.message.HttpResponse;
import blue.http.core.message.View;
import blue.http.internal.core.net.render.FreeMarkerRender;
import blue.http.internal.core.net.render.Render;
import blue.http.internal.core.util.HttpServerUtil;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-14
 */
public class ViewResponseHandler implements ResponseHandler {
	private final Render render;

	public ViewResponseHandler(String viewRoot) {
		this.render = new FreeMarkerRender(viewRoot);
	}

	@Override
	public boolean accepted(Object target) {
		return target != null && target instanceof View;
	}

	@Override
	public void handle(Channel ch, HttpRequest request, HttpResponse response) {
		View view = (View) response.getResult();
		if (view.getRedirect() != null && !view.getRedirect().isEmpty()) {
			HttpServerUtil.sendRedirect(ch, view.getRedirect());
			return;
		}
		String html = render.render(view.getView(), view.getModel());
		if (html == null || html.isEmpty()) {
			HttpServerUtil.sendError(ch, HttpResponseStatus.INTERNAL_SERVER_ERROR);
			return;
		}

		response.setResult(html);
		HttpServerUtil.sendText(ch, request, response, true);

	}
}
